package sortStudy;

import java.util.Arrays;

public class MergeSort2 {

    /**
     * 归并排序算法
     * @param args
     */
    public static void main(String[] args) {
        int [] arr = {9,8,7,6,5,4,3,2,1};
        int [] temp = new int[arr.length];
        MergeSort2 main = new MergeSort2();
        main.sort(arr, 0, arr.length - 1, temp);
        Arrays.toString(arr);
    }

    private void sort(int[] arr, int left, int right, int[] tmp){
        if (left < right){
            int mid = (left + right) >> 1;
            sort(arr, left, mid, tmp);
            sort(arr, mid + 1, right, tmp);
            merge(arr, left, mid, right, tmp);
        }
    }

    private void merge(int[] arr,int left,int mid, int right,int[] tmp){
        int i = left;
        int j = mid + 1;
        int index = left;
        while (i <= mid && j <= right){
            if (arr[i] <= arr[j]){
                tmp[index++] = arr[i++];
            } else {
                tmp[index++] = arr[j++];
            }
        }
        while (i <= mid){
            tmp[index++] = arr[i++];
        }
        while (j <= right){
            tmp[index++] = arr[j++];
        }

        while (left <= right){
            arr[left] = tmp[left];
            left++;
        }
    }
}
